<!-- 房产信息 - 基础设置 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <el-form-item label="楼栋名称" prop="name">
      <el-input
        v-model="formData.name"
        :autosize="{ minRows: 1, maxRows: 1 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="64"
        placeholder="请输入房产名称"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="楼栋地址" prop="address">
      <el-input
        v-model="formData.address"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="64"
        placeholder="请输入楼栋地址"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="房产分类" prop="categoryId">
      <el-cascader
        v-model="formData.categoryId"
        :options="categoryList"
        :props="defaultProps"
        class="w-80"
        clearable
        filterable
        placeholder="请选择房产分类"
      />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/house/house/spu'
import * as HouseCategoryApi from '@/api/house/house/category'
import { CategoryVO } from '@/api/house/house/category'

defineOptions({ name: 'ProductSpuInfoForm' })
const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const message = useMessage() // 消息弹窗

const formRef = ref() // 表单 Ref
const formData = reactive<Spu>({
  name: '', // 房产名称
  address: '', //地址
  categoryId: undefined,
  oldArea: 0,
  area: 0
})
const rules = reactive({
  name: [required],
  categoryId: [required],
})

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
  },
  {
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【基础设置】不完善，请填写相关信息')
    emit('update:activeName', 'info')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

/** 初始化 */
const categoryList = ref<CategoryVO[]>([]) // 房产分类树
onMounted(async () => {
  // 获得分类树
  const data = await HouseCategoryApi.getCategoryList({})
  categoryList.value = handleTree(data, 'id')
})
</script>
